/**
 * Copyright (C) 2009, 2010 SC 4ViewSoft SRL
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.mango.android.chart;

import org.achartengine.chart.ScatterChart;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.activity.chart.NvChart;

/**
 * The line chart rendering class.
 */
public class UpLineChart extends UpXYChart
{

	/**
	 * Builds a new line chart instance.
	 * 
	 * @param dataset the multiple series dataset
	 * @param renderer the multiple series renderer
	 */
	public UpLineChart(XYMultipleSeriesDataset dataset,
			XYMultipleSeriesRenderer renderer)
	{
		super(dataset, renderer);
	}

	public UpLineChart(XYMultipleSeriesDataset dataset,
			XYMultipleSeriesRenderer renderer, NvChart nvChart)
	{
		// TODO Auto-generated constructor stub
		super(dataset, renderer, nvChart);
	}

	/**
	   * The graphical representation of the XY chart.
	   * 
	   * @param canvas the canvas to paint to
	   * @param x the top left x value of the view to draw to
	   * @param y the top left y value of the view to draw to
	   * @param width the width of the view to draw to
	   * @param height the height of the view to draw to
	   */
	@Override
	public void draw(Canvas canvas, int x, int y, int width, int height)
	{

		Paint paint = new Paint();
		paint.setAntiAlias(mRenderer.isAntialiasing());

		initSize(width, height);

		int left = x + leftWidth;
		int top = y + topHeight;
		int right = x + width - rightWidth;
		int bottom = y + height - bottomHeight;

		if (screenR == null)
		{
			screenR = new Rect();
		}
		screenR.set(left, top, right, bottom);

		TDStockLog.d("Print_Info", "screenR:" + screenR.toShortString());

		Paint paint2 = new Paint();
		paint2.setColor(Color.BLACK);
		canvas.drawColor(Color.BLACK);

		drawTopBackground(mRenderer, canvas, left, y, right, top, paint);

		drawBackground(mRenderer, canvas, left, top, right - left, bottom
				- top, paint);//background

		drawBackgroundDottedLine(canvas, left, top, right - left, bottom
				- top, new Paint());

		if (paint.getTypeface() == null
				|| !paint.getTypeface().toString().equals(
						mRenderer.getTextTypefaceName())
				|| paint.getTypeface().getStyle() != mRenderer
						.getTextTypefaceStyle())
		{
			paint.setTypeface(Typeface.create(mRenderer
					.getTextTypefaceName(), mRenderer
					.getTextTypefaceStyle()));
		}
		Orientation or = mRenderer.getOrientation();

		double minX = mRenderer.getXAxisMin();
		double maxX = mRenderer.getXAxisMax();
		double minY = mRenderer.getYAxisMin();
		double maxY = mRenderer.getYAxisMax();
		boolean isMinXSet = mRenderer.isMinXSet();
		boolean isMaxXSet = mRenderer.isMaxXSet();
		boolean isMinYSet = mRenderer.isMinYSet();
		boolean isMaxYSet = mRenderer.isMaxYSet();
		//	    double xPixelsPerUnit = 0;//by zhengan
		//	    double yPixelsPerUnit = 0;//by zhengan
		int sLength = mDataset.getSeriesCount();
		String[] titles = new String[sLength];
		for (int i = 0; i < sLength; i++)
		{
			XYSeries series = mDataset.getSeriesAt(i);
			titles[i] = series.getTitle();
			if (series.getItemCount() == 0)
			{
				continue;
			}
			if (!isMinXSet)
			{
				double minimumX = series.getMinX();
				minX = Math.min(minX, minimumX);
				calcRange[0] = minX;
			}
			if (!isMaxXSet)
			{
				double maximumX = series.getMaxX();
				maxX = Math.max(maxX, maximumX);
				calcRange[1] = maxX;
			}

			/* if(!isMinYSet){
			  double minimumY = series.getMinY();
			      minY = Math.min(minY, (float) minimumY);
			      calcRange[2] = minY;
			 }
			 
			 if(!isMaxYSet){
			  double maximumY = series.getMaxY();
			      maxY = Math.max(maxY, (float) maximumY);
			      calcRange[3] = maxY;	    	  
			 }*/

			double minimumY = series.getMinY();
			/*  if(!isEqual(minY, 0)){
				  minY = Math.min(minY, (float) minimumY);
				  calcRange[2] = minY;
			  }
			  else{
				  minY = minimumY;
				  calcRange[2] = minimumY;
			  }*/

			minY = getMinY(minY, minimumY);

			double maximumY = series.getMaxY();
			maxY = Math.max(maxY, (float) maximumY);
			calcRange[3] = maxY;

		}
		/*	    if (!isEqual(maxX, maxX)) {
		//	      xPixelsPerUnit = (right - left) / (maxX - minX);
			    	int count = this.mDataset.getSeriesAt(0).getItemCount();
			    	if(count == 0){
			    		return ;
			    	}
			    	xPixelsPerUnit = 1.0f * (right - left) / (count-1);
			    }*/

		if (maxX - minX != 0)
		{
			//	      xPixelsPerUnit = (right - left) / (maxX - minX);
			int count = this.mDataset.getSeriesAt(0).getItemCount();
			if (count == 0)
			{
				return;
			}
			xPixelsPerUnit = 1.0f * (right - left) / (count - 1);
		}

		if (!isEqual(maxY, minY))
		{
			yPixelsPerUnit = (float) ((bottom - top) / (maxY - minY));

		}

		TDStockLog.d("Print_Info", "maxY: " + maxY);

		TDStockLog.d("Print_Info", "minY: " + minY);

		boolean hasValues = true;//by zhengan

		/////////////by zhengan   调整了绘线的位置，调到了绘制坐标的后面

		//draw label and grid
		boolean showLabels = mRenderer.isShowLabels() && hasValues;
		boolean showGrid = mRenderer.isShowGrid();
		if (showLabels || showGrid)
		{

			if (showLabels)
			{
				paint.setColor(mRenderer.getLabelsColor());
				paint.setTextSize(mRenderer.getLabelsTextSize());
				paint.setTextAlign(Align.CENTER);//by zhengan origin

				drawXLabels(canvas, paint);

				drawYLabels(canvas, paint);

			}

		}

		//如果是一周的情况，在没有触摸的时候没有竖线
		if (getIsWeekChart() && !getIsTouching())
		{
			TDStockLog.d("Print_Info", "isWeekChart verticlaline");
			drawWeekChartVerticalLine(canvas, screenR.top, screenR.bottom,
					new Paint());
		}

		if (getIsTouching())
		{
			float xLocation = getXLocation(getIndex());

			TDStockLog.d("Print_Info", "xLocation:" + xLocation);

			drawVerticalLine(canvas, xLocation, top, bottom);

		}

		//draw series
		for (int i = 0; i < sLength; i++)
		{

			XYSeries series = mDataset.getSeriesAt(i);
			if (series.getItemCount() == 0)
			{
				continue;
			}
			hasValues = true;
			SimpleSeriesRenderer seriesRenderer = mRenderer
					.getSeriesRendererAt(i);

			int originalValuesLength = series.getItemCount();
			float[] points = null;
			int valuesLength = originalValuesLength;
			int length = valuesLength * 2;

			/////////////////////////////
			//去掉前一段为0的区域        	
			TDStockLog.d("Print_Info", "length:" + length);

			int k = 0;

			while (k < originalValuesLength && isEqual(series.getY(k), 0))
			{

				k += 1;
			}
			TDStockLog.d("Print_Info", "k:" + k);
			length = length - k * 2;
			TDStockLog.d("Print_Info", "length:" + length);

			if (length < 2)
			{
				continue;
			}

			points = new float[length];
			for (int j = 0; j < length; j += 2)
			{
				int index = j / 2 + k;
				//        points[j] = (float) (left + xPixelsPerUnit * (series.getX(index) - minX));
				points[j] = (float) (left + xPixelsPerUnit * index);
				points[j + 1] = (float) (bottom - yPixelsPerUnit
						* (series.getY(index) - minY) - 0.1f);
			}
			/////////////////////////////////
			drawSeries(canvas, paint, points, seriesRenderer, Math.min(
					bottom, (float) (bottom + yPixelsPerUnit * minY)), i);
			if (isRenderPoints(seriesRenderer))
			{
				ScatterChart pointsChart = new ScatterChart(mDataset,
						mRenderer);
				pointsChart.drawSeries(canvas, paint, points,
						seriesRenderer, 0, i);
			}
			paint.setTextSize(mRenderer.getChartValuesTextSize());
			if (or == Orientation.HORIZONTAL)
			{
				paint.setTextAlign(Align.CENTER);
			}
			else
			{
				paint.setTextAlign(Align.LEFT);
			}
			if (mRenderer.isDisplayChartValues())
			{
				drawChartValuesText(canvas, series, paint, points, i);
			}

			TDStockLog.d("Print_Info", "bottom: " + bottom);
			TDStockLog.d("Print_Info", "yPixelsPerUnit: " + yPixelsPerUnit);
			TDStockLog.d("Print_Info", "y: "
					+ (float) (bottom - yPixelsPerUnit
							* (series.getY(0) - minY)));
		}

		if (getIsTouching())
		{
			//	    	float xLocation = (float) ((mDataset.getSeriesAt(0).getX(NvChart.index)-calcRange[0]) * xPixelsPerUnit);

			float xLocation = getXLocation(getIndex());

			drawCircle(canvas, xLocation, getYLocation(getIndex()));

			drawTopBm(canvas, getBmX(xLocation), y, bmWidth, topHeight,
					getYValue(getIndex()));

		}

		/* if(getIsTouching())
		 {  
		//	    	float xLocation = (float) ((mDataset.getSeriesAt(0).getX(NvChart.index)-calcRange[0]) * xPixelsPerUnit);
		 	
		 	float xLocation = getXLocation(getIndex()); 
		 	
		 	TDStockLog.d("Print_Info", "xLocation:"+xLocation);
		 	
		 	drawVerticalLine(canvas, xLocation, top, bottom);
		 	
		 	drawCircle(canvas, xLocation, getYLocation(getIndex()));
		 	
		 	drawTopBm(canvas, getBmX(xLocation), y, bmWidth, topHeight, getYValue(getIndex()));    	
		 	
		 }*/

	}

	/**
	   * The graphical representation of a series.
	   * 
	   * @param canvas the canvas to paint to
	   * @param paint the paint to be used for drawing
	   * @param points the array of points to be used for drawing the series
	   * @param seriesRenderer the series renderer
	   * @param yAxisValue the minimum value of the y axis
	   * @param seriesIndex the index of the series currently being drawn
	   */
	public void drawSeries(Canvas canvas, Paint paint, float[] points,
			SimpleSeriesRenderer seriesRenderer, float yAxisValue,
			int seriesIndex)
	{
		int length = points.length;
		XYSeriesRenderer renderer = (XYSeriesRenderer) seriesRenderer;
		float lineWidth = paint.getStrokeWidth();
		paint.setStrokeWidth(renderer.getLineWidth());
		if (renderer.isFillBelowLine())
		{
			paint.setColor(renderer.getFillBelowLineColor());
			int pLength = points.length;
			float[] fillPoints = new float[pLength + 4];
			System.arraycopy(points, 0, fillPoints, 0, length);
			fillPoints[0] = points[0] + 1;
			fillPoints[length] = fillPoints[length - 2];
			fillPoints[length + 1] = yAxisValue;
			fillPoints[length + 2] = fillPoints[0];
			fillPoints[length + 3] = fillPoints[length + 1];
			paint.setStyle(Style.FILL);
			drawPath(canvas, fillPoints, paint, true);
		}
		paint.setColor(seriesRenderer.getColor());
		paint.setStyle(Style.STROKE);
		drawPath(canvas, points, paint, false);
		paint.setStrokeWidth(lineWidth);
	}

}
